import $ from 'jquery';
import CookieUtil from './utils/CookieUtil';
import HandleSearch from './utils/HandleSearch';
import styles from '../styles/App.css';
import React,{ Component } from 'react';
import { hashHistory } from 'react-router';
import { List, InputItem, Button, Toast, Picker, WhiteSpace } from 'antd-mobile';
import { createForm } from 'rc-form';
const Item = List.Item;

const fonts = [
    // {label:'黑体',value: '80dbcc4aefd441a8b38fc9d75bcf259b'},
    // {label:'幼圆',value: '7c17ef5824ee4ad3841edc68d66d58de'},
    // {label:'行楷',value: 'c9f47cfed2db4da981d36268c9720388'},
    // {label:'楷体',value: '3761ab7f6c1b464dbd2fcbae26de6de1'},
    // {label:'隶书',value: '6b156cbfdbee46e898248285d9af0083'},
    // {label:'Verdana',value: '5afac8f8f629d910dce29e39'},
    // {label:'SymbolMW',value: '5afacc63f629d910dce29e3b'},
    // {label:'TimesNewRoman',value: '5afaa9c1f629d910dce29e1b'},
    // {label:'Impact',value: '5af2acd8f629d91a4c8129d2'},
    // {label:'CourierNew',value: '5afacc72f629d910dce29e3c'},
    {label:'segoe',value: '1'},
    {label:'georgia',value: '2'},
    {label:'comic',value: '3'},
    {label:'impact',value: '4'},
    {label:'verdana',value: '5'},
];

class PerfectInfoForm extends Component {

    constructor(props){
        super(props);
        this.state = {
            userInfo: {
                company: '',
                phone: '',
                marking: '',
                fontFamily: '',
                openid: '',
            },
            markingErr: false,
            yzkFontFace: '',
            yzkFontFamily: '',
        }
    }

    componentWillMount() {

        const openid = CookieUtil.getCookie('openid');
        if(!openid){
            const params = HandleSearch.parseQueryString(window.location.href);
            const { code, state } = params;
            alert(code);
            alert(state);
            $.ajax({
                url: `/handleCode?code=${code}&state=${state}`,
                type: 'GET',
                success: (response)=>{
                    console.log(response);
                    /*const {openid} = response;
                    $.ajax({
                        url: `/checkSubscribe`,
                        type: 'POST',
                        data: {openid},
                        dataType: 'json',
                        success: (res)=>{
                            alert(JSON.stringify(res));
                        },
                        error: (err)=>{
                            throw err;
                        },
                    });*/
                    if(response.data === 0){
                        hashHistory.push('/App/Subscribe');
                        return;
                    }
                    if(response.orderid){
                        hashHistory.push('/App/OrderSuccess');
                    } else {

                        this.props.form.setFieldsValue({
                            marking: response.marking,
                        });
                        const flag = /^[a-zA-Z\s]{1,5}$/.test(response.marking);//
                        if (!response.marking || response.marking.length > 5 || !flag) {
                            this.setState({
                                markingErr: true,
                                userInfo: response,
                            });
                        } else {
                            this.setState({
                                userInfo: response,
                            });
                        }
                    }
                },
                error: (err)=>{
                    if(err){
                        throw err;
                    }
                }
            });
        } else {
            $.ajax({
                url: `/getInfo?openid=${openid}`,
                type: 'GET',
                success: (response)=>{
                    console.log(response);
                    const { company, phone, marking, font_family:fontFamily, order_id } = response;
                    if(order_id){
                        hashHistory.push('/App/OrderSuccess');
                    } else {
                        this.props.form.setFieldsValue({
                            company,
                            phone,
                            marking,
                            fontFamily,
                        });
                        if(marking && marking.length > 5){
                            this.setState({
                                userInfo: {
                                    company,
                                    phone,
                                    marking,
                                    fontFamily,
                                    openid,
                                },
                                markingErr: true,
                            });
                        } else {
                            this.setState({
                                userInfo: {
                                    company,
                                    phone,
                                    marking,
                                    fontFamily,
                                    openid,
                                },
                            });
                        }

                    }
                },
                error: (err)=>{
                    throw err;
                }
            });
        }
    }

    onSubmit(){
        this.props.form.validateFields({ force: true }, (error) => {
            const fontFamily = this.props.form.getFieldValue('fontFamily');
            const marking = this.props.form.getFieldValue('marking');
            const phone = this.props.form.getFieldValue('phone');
            const markingFlag = /^[a-zA-Z\s]{1,5}$/.test(marking);
            // const phoneFlag = /^(0[0-9]{2,3}\-?)?([2-9][0-9]{6,7})+(\-?[0-9]{1,4})?$|^1[3|4|5|7|8][0-9]{9}$/;
            // if (phone && !phoneFlag) {
            //     Toast.fail('电话输入有误', 2);
            //     return;
            // }
            // if(!marking || marking.length === 0){
            //     Toast.fail('请输入标签文字', 2);
            //     return;
            // }
            if(marking && marking.length > 5){
                Toast.fail('标签文字不超过5个字符', 2);
                return;
            // } else if(marking && marking.length === 0){
            }
            if (marking && !markingFlag) {
                Toast.fail('标签文字只能为英文和空格', 2);
                return;
            }
            if(!fontFamily){
                Toast.fail('请选择标签字体', 2);
                return;
            }
            if (!error) {
                console.log(this.props.form.getFieldsValue());
                let { company, fontFamily, marking, phone} = this.props.form.getFieldsValue();
                let font = '';
                for(let item of fonts){
                    if(item.value === fontFamily[0]){
                        font = item.label;
                        break;
                    }
                }

                const openid = this.state.userInfo.openid;
                $.ajax({
                    url: '/submitOrder',
                    type: 'POST',
                    data: { company, fontFamily: fontFamily[0], font, marking, phone, openid },
                    dataType: 'json',
                    success: (response)=>{
                        console.log(response);
                        if(response.code == 200){
                            // this.props.changeTitle('成功');
                            hashHistory.push('/App/OrderSuccess');//跳转路由
                        } else {
                            // this.props.changeTitle('失败');
                            hashHistory.push('/App/OrderError');//跳转路由
                        }

                    },
                    error: (err)=>{
                        throw err;
                    }
                });

            } else {
                throw error;
            }
        });

        /*const openid = CookieUtil.getCookie('openid');
        $.ajax({
            url: `/checkSubscribe`,
            type: 'POST',
            data: {openid},
            dataType: 'json',
            success: (res)=>{
                alert(JSON.stringify(res));
            },
            error: (err)=>{
                throw err;
            },
        });*/

        console.log(this.props.form.getFieldsValue());
    }

    /*onReset(){
        this.props.form.resetFields();
    }*/

    validatePhone(rule, value, callback){
        const regexp = /^(0[0-9]{2,3}\-?)?([2-9][0-9]{6,7})+(\-?[0-9]{1,4})?$|^1[3|4|5|7|8][0-9]{9}$/;
        if(!value || regexp.test(value)){
            callback();
        } else {
            callback(new Error('电话输入有误'));
        }
    }

    validateMarking(rule, value, callback){
        const flag = /^[a-zA-Z\s]{1,5}$/.test(value);
        if (value && value.length <= 5 && flag) {
            callback();
            return;
        }
        if (value && value.length > 5) {
            callback(new Error('标签文字不超过5个字符'));
            return;
        }
        if (value && !flag) {
            callback(new Error('标签文字只能为英文和空格'));
            return;
        }
    }

    changeMarking(value){
        this.props.form.setFieldsValue({
            marking: value
        });
        const flag = /^[a-zA-Z\s]{1,5}$/.test(value);
        if(!value || value.length > 5 || !flag){
            this.setState({
                markingErr: true,
            });
        } else {
            this.setState({
                markingErr: false,
            });
        }
    }

    changFontFamily(){
        const fontFamily = this.props.form.getFieldValue('fontFamily');
        console.log(fontFamily);
        const marking = this.props.form.getFieldValue('marking');
        if(!marking){
            this.props.form.setFieldsValue({
                fontFamily: [],
            });
            Toast.fail('请填写标签文字', 2);
            return;
        }
        const params = {
            ApiKey: '1989013c90b9c9d3372998d53567cc63',
            AccessKey: fontFamily[0],
            Content: marking,
        }
        $.ajax({
            type: 'POST',
            url: '/handleFontFamily',
            data: params,
            dataType: 'json',
            success: (result)=>{
                console.log(result);
                this.setState({
                    yzkFontFace: result.FontFace,
                    yzkFontFamily: result.FontFamily,
                });
            },
            error: (err)=>{
                throw err;
            },
        });
    }

    render(){
        const { getFieldProps, getFieldError } = this.props.form;


        return (
            <div className="PerfectInfo">
                <style>{this.state.yzkFontFace}</style>
                <form>
                    <List
                        renderHeader={()=> '联系方式'}
                    >
                        <InputItem
                            clear
                            extra="非必填项"
                            /*placeholder="请输入公司"*/
                            {...getFieldProps('company', {
                                /*initialValue: this.state.userInfo.company || '',*/
                            })}
                        >
                            公司：
                        </InputItem>
                        <InputItem
                            clear
                            extra="非必填项"
                            type="number"
                            /*placeholder="请输入电话"*/
                            error={!!getFieldError('phone')}
                            onErrorClick={()=>{
                                Toast.fail(getFieldError('phone').join(''),1);
                            }}
                            {...getFieldProps('phone', {
                                /*initialValue: this.state.userInfo.phone || '',*/
                                rules: [
                                    {required: false},
                                    { validator: this.validatePhone.bind(this) },
                                ]
                            })}
                        >
                            电话：
                        </InputItem>
                    </List>

                    <List
                        renderHeader={() => '定制信息'}
                        renderFooter={() => getFieldError('marking') && getFieldError('marking').join(',')}
                    >
                        <InputItem
                            {...getFieldProps('marking', {
                                /*initialValue: this.state.userInfo.marking || '',*/
                                rules: [
                                    { required: true, message: '请输入标签文字' },
                                    { validator: this.validateMarking.bind(this) },
                                ],
                            })}
                            clear
                            extra="必填项"
                            error={this.state.markingErr}
                            onErrorClick={() => {
                                Toast.fail('标签文字只能为英文和空格，不为空，且不超过5个字符',3);
                            }}
                            /*placeholder="请输入标签文字"*/
                            onChange={this.changeMarking.bind(this)}
                        >标签文字：</InputItem>
                        <Picker
                            data={fonts}
                            cols={1}
                            {...getFieldProps('fontFamily')}
                            onOk={this.changFontFamily.bind(this)}
                        >
                            <Item arrow="horizontal">标签字体：</Item>
                        </Picker>
                        <WhiteSpace size="xl"/>
                        <div className={styles['font-family']} style={{fontFamily: this.state.yzkFontFamily}}>
                            {this.props.form.getFieldValue('marking')}
                        </div>
                        <WhiteSpace size="xl"/>

                        <Button
                            type="primary"
                            onClick={this.onSubmit.bind(this)}
                        >提交订单</Button>
                        {/*<Button inline style={{ marginLeft: '1rem' }} onClick={this.onReset.bind(this)}>重置</Button>*/}

                    </List>
                </form>
            </div>
        );

    }

}

const PerfectInfo = createForm()(PerfectInfoForm);
export default PerfectInfo;